﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;

namespace T04WebService
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string name)
        {
            return "Hello"+name;
        }

        [WebMethod]
        public void Login(string username, string password)
        {
            string json = JsonConvert.SerializeObject(new{Status = "failed"});//匿名内部类 这个类作为对象被序列化转为json
            if (UserDao.LoginCheck(username, password) > 0)
            {
                //返回登陆用户完整信息,处理中文信息
                json = JsonConvert.SerializeObject
                    (UserDao.GetUserByUsername(username),
                    Formatting.Indented, new JsonSerializerSettings
                    { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii });
            }
            //输出json数据
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding =
                System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(json);
            Context.Response.End();
        }

            [WebMethod]
        public void Resgister(string username, string password,
                string nickname, bool isAdmin)
        {
            string json = JsonConvert.SerializeObject(new
            {
                Status = "failed"
            });

            User user = new User();
            user.Username = username;
            user.Password = password;
            user.Nickname = nickname;
            user.IsAdmin = isAdmin;

            if (UserDao.Insert(user) > 0) {
               json = JsonConvert.SerializeObject(new { Status = "success" });
            }

            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding =
                System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(json);
            Context.Response.End();
        }
    }
}
